﻿using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml.Linq;

namespace Core
{
    public static class FileService
    {
        public static XElement GetRootNode(string file)
        {
            using (var fileStream = new FileStream(file, FileMode.Open))
            {
                var xDocument = XDocument.Load(fileStream);
                return xDocument.Root;
            }
        }

        public static Language GetLocaleDetails(string filePath)
        {
            using (var fileStream = new FileStream(filePath, FileMode.Open))
            {
                var xDocument = XDocument.Load(fileStream);

                var descendants = xDocument.Descendants("root").Descendants()
                    .Where(d => d.Name == "data")
                    .AsQueryable();

                var language = descendants
                    .Single(d => d.Attribute("name").Value == "ResourceLanguage")
                    .Elements()
                    .Single(e => e.Name == "value")
                    .Value;
                    
                var direction = descendants
                    .Single(d => d.Attribute("name").Value == "ResourceFlowDirection")
                    .Elements()
                    .Single(e => e.Name == "value")
                    .Value;

                return new Language
                {
                    Direction = direction.Trim(),
                    Locale = language.Trim()
                }; 
            }
        }

        public static IEnumerable<string> GetFileNames(string folderPath)
        {
            return Directory.GetFiles(folderPath, "*.resx");
        }
    }
}
